package aim.orderentry.database.Adapter;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.location.Location;

public class MySqliteManager {

	public static final String 	KEY_ID = "_id";
	public static final String 	KEY_LONG = "_long";
	public static final String 	KEY_LAT = "_lat";
	public static final String 	KEY_TIME = "_time";
	
	public static final String 	DATABASE_NAME = "K";
	public static final String 	DATABASE_TABLE = "locations";
	public static final int 	DATABASE_VERSION = 1;
	
	public static final String QUERY = "create table " + DATABASE_TABLE + " (_id integer primary key autoincrement, _long real, _lat real, _time text)"; 
	
	private Context 			mContext;
	private SQLiteDatabase		mSqlite;
	private MySqliteOpenHelper 	mSqliteHelper;
	
	public MySqliteManager(Context context) {
		this.mContext = context;	 
	}
	
	public MySqliteManager open() {
		mSqliteHelper = new MySqliteOpenHelper(mContext, DATABASE_NAME, null, DATABASE_VERSION);
		return this;
	}
	
	public boolean inserData(Location location, String time) {
		mSqlite = mSqliteHelper.getWritableDatabase();
		
		ContentValues cv = new ContentValues();
		
		cv.put(KEY_LAT, location.getLatitude());
		cv.put(KEY_LONG, location.getLongitude());
		cv.put(KEY_TIME, time);
		
		boolean result = mSqlite.insert(DATABASE_TABLE, null, cv) > -1  ? true : false;
		mSqlite.close();
		return result;
	}
	
	public Cursor getAllData() {
		return mSqlite.query(DATABASE_TABLE, null, null, null, null, null, null);
	}
	
	private class MySqliteOpenHelper extends SQLiteOpenHelper {

		public MySqliteOpenHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(QUERY);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			db.execSQL("drop table if exists " + DATABASE_TABLE);
			onCreate(db);
		}
		
	}
}
